package de.tum.activities.ExamApp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.xmlrpc.android.XMLRPCException;

import de.tum.ExamApp.R;
import de.tum.Misc.Variables;
import de.tum.activities.ExamEvaluation.ExamEvaluationActivity;
import de.tum.activities.Login.LoginActivity;
import de.tum.activities.SecondExamEvaluation.SecondExamEvaluationActivity;
import de.tum.activities.StatsApp.StatsActivity;
import de.tum.control.Synchronizer;
import de.tum.datatypes.Exam;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This activity provides an overview over all exams.
 * 
 * They are displayed in a listview.
 * 
 * 
 * @author Rupert
 *
 */
public class ExamAppActivity extends Activity implements OnItemClickListener{
	
	/**
	 * Greeting textView
	 */
	private TextView welcomingTextView;
	
	/**
	 * ListView containing the exams
	 */
	private ListView examListView;
	
	/**
	 * start Activity for result -> 
	 */
	private static final int evaluationError = 0;
	private static final int secondEvaluation = 1;
	
	int userId;
	private List<Exam> exams = new ArrayList<Exam>();
	
	ProgressDialog progressDialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        welcomingTextView = (TextView) findViewById(R.id.main_welcoming);
        
        SharedPreferences localSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        String username = localSharedPreferences.getString("username", "???");
        userId = localSharedPreferences.getInt("userId", -1);
        
        welcomingTextView.setText(getString(R.string.main_welcoming_text, username));
        
        Date test = new GregorianCalendar(2012, 12, 31, 23, 59).getTime();
        
        
        getExams();
        
        examListView = (ListView) findViewById(R.id.main_examListView);
        examListView.setAdapter(new ExamsAdapter(getApplicationContext(), R.layout.list_item_exam_overview, exams));
        examListView.setOnItemClickListener(this);
    }



    private void getExams() {
    	
    	progressDialog = ProgressDialog.show(ExamAppActivity.this, "Server-Connection", "Login to server...");
		
    	
		Thread t = new Thread() {

			public void run() {
		    	try {
		        	Synchronizer sync = new Synchronizer();
		        	exams = sync.getExams(userId);
				} catch (XMLRPCException e) {
					Log.d("RESULT-EXAM-ID", "EXCEPTION");
					e.printStackTrace();
				}

				progressDialog.dismiss();
			}

		};
		
		t.start();
		
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	private class ExamsAdapter extends ArrayAdapter<Exam>{

		private Context context;
		private List<Exam> exams;
		
		public ExamsAdapter(Context context, int textViewResourceId, List<Exam> exams) {
					super(context, textViewResourceId, exams);		
					this.context = context;
					this.exams = exams;
		}
		
		public View getView(int position, View convertView, ViewGroup parent){
			View view = convertView;
	        if (view == null) {
	            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.list_item_exam_overview, null);
	        }
	        
	        Exam curExam = exams.get(position);
	        if(curExam != null){
	        	SimpleDateFormat simpleDateFormat = Variables.formats[1];
	        	
	        	TextView examNameTextView = (TextView) view.findViewById(R.id.main_list_view_exam_title);
	        	examNameTextView.setText(curExam.getSubjectName());
	        	
	        	TextView examDateTextView = (TextView) view.findViewById(R.id.main_list_view_exam_date);
	        	examDateTextView.setText(simpleDateFormat.format(curExam.getExamDate()));
	        	
	        	TextView evaluationBeginDateTextView = (TextView) view.findViewById(R.id.main_list_view_evaluationBegin);
	        	evaluationBeginDateTextView.setText(simpleDateFormat.format(curExam.getEvaluationBeginDate()));
	        	
	        	TextView evaluationEndDateTextView = (TextView) view.findViewById(R.id.main_list_view_evaluationEnd);
	        	evaluationEndDateTextView.setText(simpleDateFormat.format(curExam.getEvaluationEndDate()));
	        	
	        	int maxNbrOfCorrections = curExam.getNumberOfParticipants() * 2 * curExam.getNumberOfExercises();
	        	
	        	Synchronizer Sync = new Synchronizer();
	        	int correctedExercises = 0;
	        	try {
					correctedExercises = Sync.getNumberExercisesFirstAndSecondCorrected(curExam.getId());
				} catch (XMLRPCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	
	        	ProgressBar p = (ProgressBar) view.findViewById(R.id.main_list_view_progressBar);
	        	p.setMax(maxNbrOfCorrections);
			    p.setProgress(correctedExercises); // spent/budget
	        	
	        }
	        
			return view;
		}
	}



	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
		final CharSequence[] items = this.getApplicationContext().getResources().getStringArray(R.array.main_exam_click_dialog);
		AlertDialog.Builder listBuilder = new AlertDialog.Builder(this);

		Log.d("Add Evaluation Click", "Exam Item: "+position);

		final int examPosInListView = position;
		
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			Intent newActivity;
			public void onClick(DialogInterface dialog, int item) {
				Exam clickedExam;
				switch(item){
				case 0: //add evaluation
					clickedExam =  exams.get(examPosInListView);
					
					Date curDate = new Date();
					
					if(curDate.before(clickedExam.getEvaluationBeginDate())){
						Toast.makeText(getApplicationContext(), "No evaluation before the evaluation begin date", Toast.LENGTH_LONG).show();
						return;
					}
					if(curDate.after(clickedExam.getEvaluationEndDate())){
						Toast.makeText(getApplicationContext(), "No evaluation after the evaluation end date", Toast.LENGTH_LONG).show();
						return;
					}
					
					newActivity = new Intent(getApplicationContext(), ExamEvaluationActivity.class);
					newActivity.putExtra("examID", clickedExam.getId());
					newActivity.putExtra("examName", clickedExam.getSubjectName());	   	   
					startActivityForResult(newActivity, evaluationError);
					break;
				case 1: //add second evaluation
					clickedExam =  exams.get(examPosInListView);
					
					Date curSecondCorrectionDate = new Date();
					
					if(curSecondCorrectionDate.before(clickedExam.getEvaluationBeginDate())){
						Toast.makeText(getApplicationContext(), "No evaluation before the evaluation begin date", Toast.LENGTH_LONG).show();
						return;
					}
					if(curSecondCorrectionDate.after(clickedExam.getEvaluationEndDate())){
						Toast.makeText(getApplicationContext(), "No evaluation after the evaluation end date", Toast.LENGTH_LONG).show();
						return;
					}
					
					newActivity = new Intent(getApplicationContext(), SecondExamEvaluationActivity.class);
					newActivity.putExtra("examID", clickedExam.getId());
					newActivity.putExtra("examName", clickedExam.getSubjectName());	   	   
					startActivityForResult(newActivity, secondEvaluation);
					break;
				case 2: //view statistics
					clickedExam =  exams.get(examPosInListView);
					
					newActivity = new Intent(getApplicationContext(), StatsActivity.class);
					newActivity.putExtra("examID", clickedExam.getId());
					newActivity.putExtra("examName", clickedExam.getSubjectName());	 
					startActivity(newActivity);
					break;			
				}
				
			}			
		};
		
		listBuilder.setTitle(R.string.options);		
		listBuilder.setItems(items, listener);
		AlertDialog listChoice = listBuilder.create();
		listChoice.show();
	}
	
	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
	  super.onActivityResult(requestCode, resultCode, data); 
	  switch(requestCode) { 
	    case (evaluationError) : { 
	    	if (resultCode == ExamEvaluationActivity.RESULT_SAME_EXAM) { 
		    	
		      	Intent newActivity = new Intent(getApplicationContext(), ExamEvaluationActivity.class);
				newActivity.putExtra("examID", data.getIntExtra("examID", -1));
				newActivity.putExtra("examName", data.getStringExtra("examName"));	   	   
				startActivityForResult(newActivity, evaluationError);
	    	}else if (resultCode == ExamEvaluationActivity.RESULT_SAME_STUDENT) { 
		    	
		      	Intent newActivity = new Intent(getApplicationContext(), ExamEvaluationActivity.class);
				newActivity.putExtra("examID", data.getIntExtra("examID", -1));
				newActivity.putExtra("examName", data.getStringExtra("examName"));
				newActivity.putExtra("studentName", data.getStringExtra("studentName"));
				newActivity.putExtra("studentMatrNr", data.getStringExtra("studentMatrNr"));		   	   
				startActivityForResult(newActivity, evaluationError);
	    	}else if (resultCode == RESULT_OK ){
	    	  
	    	}
	    	break; 
	    }
	    case (secondEvaluation) : {
	    	if (resultCode == SecondExamEvaluationActivity.FURTHER_SECOND_CORRECTION) { 
		    	
		      	Intent newActivity = new Intent(getApplicationContext(), SecondExamEvaluationActivity.class);
				newActivity.putExtra("examID", data.getIntExtra("examID", -1));
				newActivity.putExtra("examName", data.getStringExtra("examName"));
				startActivityForResult(newActivity, secondEvaluation);
	    	}else if (resultCode == RESULT_OK ){
	    	  
	    	}
	    }
	  } 
	}
	
}